package demo.hms.util;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

@Configuration
public class TokenInterceptor implements HandlerInterceptor {
    private long refreshTime = 1000 * 60 * 60 * 3;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求拦截完成");
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");
        if(userId == null || userId.equals("")){
            // TODO 返回未登录
            returnJson(response,JSONCreate("操作失败，用户未登录"));
            return false;
        }
        Map<String,Object> map = new HashMap<>();
        map = Toekn.parseToken(session.getAttribute("token").toString());
        if(!userId.equals(map.get("userId"))){
            // TODO 返回登录信息错误
            returnJson(response,JSONCreate("操作失败，登录信息错误"));
            return false;
        }
        Long time = (Long) map.get("time");
        Long times = System.currentTimeMillis() - time;
        if(times < refreshTime){
            return true;
        }else {
            // todo 登录已过期
            returnJson(response,JSONCreate("操作失败，登录已过期"));
            return false;
        }
    }

    private String JSONCreate(String message){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("{\"code\":-1,\"message\":\"");
        stringBuffer.append(message);
        stringBuffer.append("\"}");
        return stringBuffer.toString();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("业务执行完成，无异常，已放行");
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");
        String userPassword = (String) session.getAttribute("userPassword");
        String roleName = (String) session.getAttribute("roleName");
        Long time = System.currentTimeMillis();
        session.setAttribute("time",time);
        session.setAttribute("token",Toekn.getToken(userId,userPassword,roleName,time));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("视图渲染完成");
    }

    private void returnJson(HttpServletResponse response, String result) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result);

        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }


}
